package com.huawei.petapp2.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.huawei.petapp2.R;
import com.huawei.petapp2.adapter.HistoryAdapter;
import com.huawei.petapp2.constant.HttpAddress;
import com.huawei.petapp2.entity.Result;
import com.huawei.petapp2.entity.Searchhistory;
import com.huawei.petapp2.entity.Storeitem;
import com.huawei.petapp2.utils.DateUtil;
import com.huawei.petapp2.utils.PreferenceHelper;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class SearchActivity extends AppCompatActivity {

    private static final int MSG_SEARCH = 1;
    /*private SimpleDateFormat mFormat;
    private static final int HISTORY_MAX = 5;*/
    private List<Searchhistory> mHistoryList=new ArrayList<>();//定义实物类列表
    private ListView mListView;//定义实物类列表
    private HistoryAdapter historyAdapter;//定义适配器
    private Context mContext;
    private ImageView backHome;
    private TextView searchTextview;
    private List<Storeitem> mGoodsList=new ArrayList<>();//定义实物类列表

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        //创建方法super.onCreate(),和布局加载方法setContentView()一定要放在最前面，不然可能会造成空指针现象
        super.onCreate(savedInstanceState);
        setContentView(R.layout.app_search_home);
        searchTextview=findViewById(R.id.tv_search);
        historyAdapter =new HistoryAdapter(SearchActivity.this,mHistoryList);
        //构建配置对象，完成listView之间的数据传递
        mListView=(ListView)findViewById(R.id.history_name);
        mListView.setAdapter(historyAdapter);//配置适配器
        mContext=SearchActivity.this;//初始化上下文

        showHistory();//因为这个函数用到了前面的变量，所以要放在这里
        backHome=findViewById(R.id.iv_back);//初始化返回图片
        final EditText search_et_editText= findViewById(R.id.et_search);//二级搜索界面
        //
        backHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(SearchActivity.this, HomeActivity.class);
                startActivity(intent);//启动跳转

            }
        });
        //search_et_editText.setFocusable(false);
        search_et_editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 先隐藏键盘
                    ((InputMethodManager) search_et_editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(SearchActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    //搜索具体逻辑
                    //搜索请求转交给函数去处理：
                    mGoodsList= searchGoods(String.valueOf(search_et_editText.getText()));

                    Log.i("histryss",String.valueOf(search_et_editText.getText()));
                   int  userid= PreferenceHelper.getInt("userid",getApplicationContext());
                    insertHistory(String.valueOf(search_et_editText.getText()),userid);
                    mGoodsList=searchGoods(String.valueOf(search_et_editText.getText()));
                    System.out.println("在这里打印复制后的mGoodsLIst"+mGoodsList);
                    Toast.makeText(SearchActivity.this,"按下了搜索按钮",Toast.LENGTH_SHORT).show();
                    return true;
                }
                return false;
            }
        });

        searchTextview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(SearchActivity.this,GoodResultActivity.class);
                intent.putExtra("listobj", (Serializable) mGoodsList);
                System.out.println("在传输方法中打印"+mGoodsList);
                // Log.d("JunLog",mGoodsList.toArray()+"");
                intent.setClass(SearchActivity.this,GoodResultActivity.class);
                startActivity(intent);

            }
        });

        search_et_editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }


            @Override
            public void afterTextChanged(Editable s) {

                //文字变动 ， 有未发出的搜索请求，应取消
                if(mHandler.hasMessages(MSG_SEARCH)){
                    mHandler.removeMessages(MSG_SEARCH);
                }
                //如果为空 直接显示搜索历史
                if(TextUtils.isEmpty(s)){

                }else {//否则延迟500ms开始搜索
                    mHandler.sendEmptyMessageDelayed(MSG_SEARCH,500); //自动搜索功能 删除
                }
            }
        });



    }
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            //搜索请求
            Toast.makeText(SearchActivity.this,"搜索中。。。。",Toast.LENGTH_SHORT).show();
            //search(String.valueOf(mEditTextSearch.getText()));
        }
    };

    public List<Storeitem> searchGoods(String good_name)
    {
        Result result = DateUtil.selectList(
                HttpAddress.get(HttpAddress.searchGoods(),"searchlist",good_name));
        System.out.println(result.getResult());
        List<Storeitem>storeitems=DateUtil.getList2(result);
        System.out.println("这里打印获取的storeitems"+storeitems);
        return storeitems;
    }

    /**
     * 将历史记录保存到数据库中，key=当前时间(202105023，便于排序) ，value=关键字
     * 首先要建表，创建需要存储的字段名，为了每次将选中的历史记录置顶，我增加了时间字段
     */


    public  void insertHistory(String historyName,int userid)
    {
        Result result = DateUtil.selectList(
                HttpAddress.get(HttpAddress.searchhistory(),"inserthistory",historyName,userid));
        System.out.println(result.getResult());
    }

    public  void showHistory()
    {
        Result result = DateUtil.selectList(
                HttpAddress.get(HttpAddress.searchhistory(),"listDesc"));
        System.out.println(result.getResult());
        List<Searchhistory>searchhistories=DateUtil.getList3(result);

        if(searchhistories.size()>0)
        {
            for(int i=0;i<searchhistories.size();i++)//一次最多显示五条记录
            {
                Searchhistory history=searchhistories.get(i);
                /*Result resultHis = DateUtil.selectList(
                        HttpAddress.get(HttpAddress.searchhistory(),"search",history.getHeyword()));
                if(resultHis.getResult()==null)
                {
                    mHistoryList.add(history);
                    Log.i("history",history.getHeyword());
                }*/
                mHistoryList.add(history);
                Log.i("history",history.getHeyword());
            }
            historyAdapter=new HistoryAdapter(mContext,mHistoryList);
        /*for(History history:historyList){//也可以将数据展示到具有适配器的控件中
            mHistoryList.add(history);
            historyAdapter=new HistoryAdapter(mContext,mHistoryList);

        }*/
            mListView.setAdapter(historyAdapter);
        }

    }
}